var express = require('express');
var router = express.Router();
const mysql = require('../utils/mysql');
const jiami = require('../utils/jiami');
const jwt = require('jsonwebtoken');
const { expressjwt } = require('express-jwt')
const upload = require('../utils/upload')


const secretKey = 'abc';






/**
 * 用户注册
 */
router.post('/userreg', async (req, res) => {
    //获取客户端发送的数据
    const { uid, pwd } = req.body;

    //验证数据的正确性
    if (uid.length < 2 || pwd.length < 2) {
        //有问题
        res.json({
            flag: false,
            msg: '用户名或密码格式不正确'
        })
    } else {
        //数据验证通过
        //验证用户名是否重复
        const [{ count }] = await mysql('select count(*) as count from users where username = ?', [uid]);
        if (count > 0) {
            //有重复
            res.json({
                flag: false,
                msg: '用户名已存在'
            })
        } else {
            //可以正常注册
            await mysql(
                'insert into users (username,password,createTime,updateTime) values (?,?,?,?)',
                [uid, jiami(pwd), new Date(), new Date()]
            );
            res.json({
                flag: true,
                msg: '注册成功',
            });
        }
    }


})

/**
 * 用户登录
 */
router.post('/userlogin', async (req, res) => {
    const { id, uid, pwd } = req.body;

    if (uid.length < 2 || pwd.length < 2) {
        res.json({
            flag: false,
            msg: '用户名或密码格式不正确',
        })
    } else {
        const result = await mysql('select * from users where username=? and password=?', [uid, jiami(pwd)]);
        if (result.length > 0) {
            res.json({
                flag: true,
                msg: '登录成功',
                data: {
                    token: jwt.sign({ username: uid, id: result[0].id }, secretKey, { expiresIn: 60 * 60 })
                }
            })
        } else {
            res.json({
                flag: false,
                msg: '用户名或密码不正确',
            })
        }
    }
})



router.all('*', expressjwt({
    secret: secretKey,
    algorithms: ['HS256']
}))



router.get('/getUserInfo', async function (req, res) {

    const userid = req.auth.id
    const user = await mysql('select * from userinfo where userid=?', [userid])
    if (user.length > 0) {
        res.json({
            flag: true,
            data: user[0]
        })
    } else {
        await mysql('insert into userinfo (createTime,updateTime,userid) values (now(),now(),?)', [userid])
        res.json({
            flag: true,
            data: {}
        })
    }
})

router.post('/updateUserInfo', upload.single('avatar'), async function (req, res) {
    let { nickname, gender, birthday } = req.body
    let avatar = ''
    if (req.file) {
        avatar = req.file.destination.slice(6) + req.file.filename
    }
    let userid = req.auth.id
    //更新数据库
    let arrField = []
    let arrValues = []
    if (nickname) {
        arrField.push('nickname=?')
        arrValues.push(nickname)
    }
    if (gender) {
        arrField.push('gender=?')
        if (gender == 'male') {
            arrValues.push(true)
        } else {
            arrValues.push(false)
        }
    }
    if (birthday) {
        arrField.push('birthday=?')
        arrValues.push(new Date(birthday))
    }
    if (avatar) {
        arrField.push('avatar=?')
        arrValues.push(avatar)
    }
    arrValues.push(userid)
    //UPDATE userinfo SET nickname='123' WHERE userid= 3
    //let arrField = [nickname=?,gender=?,birthday=?,avatar=?]
    let sql = 'update userinfo set updateTime=now(),';
    sql += arrField.join(',');
    sql += ' where userid=?';
    // console.log(sql);
    // console.log(userid);
    await mysql(sql, arrValues);

    // alert('更新成功')
    res.json({

        flag: true,
        msg: "更新成功"
    })
})

router.post('/addNote', async function (req, res) {
    const userid = req.auth.id

    const { title, content } = req.body

    await mysql('insert into notebook (createTime,updateTime,title,content,userid) values (?,?,?,?,?)', [new Date(), new Date(), title, content, userid])

    res.json({
        flag: true,
        msg: '更新成功'
    })
})

router.get('/updateNote', async function (req, res) {
    const userid = req.auth.id
    let { search_string, page, pre_page } = req.query

    if (!search_string) {
        search_string = ''
    }

    page = Number(page)
    if (Number.isNaN(page)) {
        page = 1
    } else {
        if (page < 1) {
            page = 1
        }
    }

    pre_page = Number(pre_page)
    if (Number.isNaN(pre_page)) {
        pre_page = 1
    }
    // } else {
    //     if (pre_page < 10) {
    //         pre_page = 10
    //     }
    // }

    // SELECT title,content FROM `notebook` WHERE userid=3
    const result = await mysql('select * from notebook where (title like ? or content like ? ) and userid = ? order by updateTime desc limit ?,? ', ['%' + search_string + '%', '%' + search_string + '%', userid, (page - 1) * pre_page, pre_page])
    // res.json({
    //     flag: true,
    //     data: result
    // })

    const [{ count: total }] = await mysql('select count(*) as count from notebook ' + 'where (title like ? or content like ?) and userid = ? ', [
        '%' + search_string + '%',
        '%' + search_string + '%',
        userid
    ])
    res.json({
        flag: true,
        data: {
            list: result,
            total: total,
            pageSize: pre_page
        }
    })

    console.log(result);

})


module.exports = router;